//
//  KwCustomerServerPlugin.m
//  kw_customer_server
//
//  Created by Payne on 2021/7/26.
//

#import "KwCustomerServerPlugin.h"
#import "PrefixHeader.h"
#import "QMChatVC/ViewController/QMChatRoomViewController.h"

@interface KwCustomerServerPlugin()
@property(nonatomic,copy) FlutterResult handlerResult;
@property(nonatomic,copy) NSDictionary *dictionary;
@end

@implementation KwCustomerServerPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar{
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"kw_customer_server" binaryMessenger:[registrar messenger]];
    KwCustomerServerPlugin *instance = [[KwCustomerServerPlugin alloc] init];
    [registrar addMethodCallDelegate:instance channel:channel];
    [[NSNotificationCenter defaultCenter]addObserver:instance selector:@selector(registerSuccess:) name:CUSTOM_LOGIN_SUCCEED object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:instance selector:@selector(registerFailure:) name:CUSTOM_LOGIN_ERROR_USER object:nil];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    if ([call.method isEqualToString:@"openKf"]) {
        NSDictionary *dict = call.arguments;
        //打开客服
        NSString *appid = [dict objectForKey:@"appId"];
        NSString *mobile = [dict objectForKey:@"mobile"];
        NSString *userId = [dict objectForKey:@"userId"];
        self.handlerResult = result;
        [QMConnect registerSDKWithAppKey:appid userName:mobile userId:userId];
    }
}

#pragma mark - notification
- (void)registerSuccess:(NSNotification *)sender {
    NSLog(@"注册成功");
    [QMConnect sdkGetWebchatScheduleConfig:^(NSDictionary * _Nonnull scheduleDic) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.dictionary = scheduleDic;
            if ([self.dictionary[@"scheduleEnable"] intValue] == 1) {
                NSLog(@"日程管理");
                [self starSchedule];
            }else{
                NSLog(@"技能组");
                [self getPeers];
            }
        });
    } failBlock:^{
        [self getPeers];
    }];
}

- (void)registerFailure:(NSNotification *)sender {
    NSLog(@"注册失败::%@", sender.object);
    QMLineError *err = sender.object;
    if (err.errorDesc.length > 0) {
        if (self.handlerResult) {
            self.handlerResult(@(NO));
            self.handlerResult = NULL;
        }
    }
}

#pragma mark - 技能组选择
- (void)getPeers {
    [QMConnect sdkGetPeers:^(NSArray * _Nonnull peerArray) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.handlerResult) {
                self.handlerResult(@(true));
                self.handlerResult = NULL;
            }
            NSArray *peers = peerArray;
            if (peers.count == 1 && peers.count != 0) {
                [self showChatRoomViewController:[peers.firstObject objectForKey:@"id"] processType:@"" entranceId:@""];
            }else {
                [self showPeersWithAlert:peers messageStr:@"选择您咨询的类型或业务部门(对应技能组)"];
            }
        });
    } failureBlock:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.handlerResult) {
                self.handlerResult(@(NO));
                self.handlerResult = NULL;
            }
        });
    }];
}

#pragma mark - 日程管理
- (void)starSchedule {
    if ([self.dictionary[@"scheduleId"] isEqual: @""] || [self.dictionary[@"processId"] isEqual: @""] || [self.dictionary objectForKey:@"entranceNode"] == nil || [self.dictionary objectForKey:@"leavemsgNodes"] == nil) {
        if (self.handlerResult) {
            self.handlerResult(@(NO));
            self.handlerResult = NULL;
        }
    }else{
        NSDictionary *entranceNode = self.dictionary[@"entranceNode"];
        NSArray *entrances = entranceNode[@"entrances"];
        if (entrances.count == 1 && entrances.count != 0) {
            if (self.handlerResult) {
                self.handlerResult(@(true));
                self.handlerResult = NULL;
            }
            [self showChatRoomViewController:[entrances.firstObject objectForKey:@"processTo"] processType:[entrances.firstObject objectForKey:@"processType"] entranceId:[entrances.firstObject objectForKey:@"_id"]];
        }else{
            [self showPeersWithAlert:entrances messageStr:@"选择您咨询的日程管理类型"];
            if (self.handlerResult) {
                self.handlerResult(@(NO));
                self.handlerResult = NULL;
            }
        }
    }
}

- (void)showPeersWithAlert: (NSArray *)peers messageStr: (NSString *)message {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"选择您咨询的类型或业务部门(对应技能组)" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertController addAction:cancelAction];
    for (NSDictionary *index in peers) {
        UIAlertAction *surelAction = [UIAlertAction actionWithTitle:[index objectForKey:@"name"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([self.dictionary[@"scheduleEnable"] integerValue] == 1) {
                [self showChatRoomViewController:[index objectForKey:@"processTo"] processType:[index objectForKey:@"processType"] entranceId:[index objectForKey:@"_id"]];
            }else{
                [self showChatRoomViewController:[index objectForKey:@"id"] processType:@"" entranceId:@""];
            }
        }];
        [alertController addAction:surelAction];
    }
    [UIApplication.sharedApplication.delegate.window.rootViewController presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 跳转聊天界面
- (void)showChatRoomViewController:(NSString *)peerId processType:(NSString *)processType entranceId:(NSString *)entranceId {
    if (!peerId.length) {
        if (self.handlerResult) {
            self.handlerResult(@(NO));
            self.handlerResult = NULL;
        }
        return;
    }
    QMChatRoomViewController *chatRoomViewController = [[QMChatRoomViewController alloc] init];
    chatRoomViewController.peerId = peerId;
    chatRoomViewController.isPush = NO;
    chatRoomViewController.avaterStr = @"";
    if ([self.dictionary[@"scheduleEnable"] intValue] == 1) {
        if (!processType.length && !entranceId.length) {
            if (self.handlerResult) {
                self.handlerResult(@(NO));
                self.handlerResult = NULL;
            }
            return;
        }
        chatRoomViewController.isOpenSchedule = true;
        chatRoomViewController.scheduleId = self.dictionary[@"scheduleId"];
        chatRoomViewController.processId = self.dictionary[@"processId"];
        chatRoomViewController.currentNodeId = peerId;
        chatRoomViewController.processType = processType;
        chatRoomViewController.entranceId = entranceId;
    }else{
        chatRoomViewController.isOpenSchedule = false;
    }
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:chatRoomViewController];
    nc.modalPresentationStyle = UIModalPresentationFullScreen;
    [UIApplication.sharedApplication.delegate.window.rootViewController presentViewController:nc animated:true completion:nil];
}

@end
